//
//  FriendList.swift
//  AppleDemo
//
//  Created by Just 花语 on 2025/10/28.
//

import SwiftUI
import SwiftData


struct FriendList: View {
    @Query(sort: \FriendIn5.name) private var friends: [FriendIn5]
    @Environment(\.modelContext) private var context
    @State private var newFriend:FriendIn5?
    var body: some View {
        NavigationSplitView{
            Group{
                if !friends.isEmpty{
                    List{
                        ForEach(friends){ friend in
                            NavigationLink(friend.name){
                                FriendDetail(friend: friend)
                            }
                        }
                        .onDelete(perform: deleteFriend)
                    }
                }else{
                    ContentUnavailableView("Add Friends", systemImage: "person.and.person")

                }
            }
            .navigationTitle("Friends")
            .toolbar{
                ToolbarItem{
                    Button("Add friend",systemImage: "plus",action: addFriend)
                        
                }
                ToolbarItem(placement: .navigationBarTrailing){
                    EditButton()
                }
            }
            .sheet(item: $newFriend){friend in
                NavigationStack {
                    FriendDetail(friend: friend,isNew: true)
                }
                .interactiveDismissDisabled()
            }
        }detail: {
            Text("Select a friend")
               .navigationTitle("Friend")
               .navigationBarTitleDisplayMode(.inline)
        }
        
    }
    private func addFriend(){
        let newFriend = FriendIn5(name: "")
        context.insert(newFriend)
        self.newFriend = newFriend
    }
    private func deleteFriend(indexes: IndexSet) {
        for index in indexes {
            context.delete(friends[index])
        }
    }
}


#Preview {
    FriendList()
        .modelContainer(SampleData.shared.modelContainer)
}
